package com.china.produce.config.shiro;

import com.china.produce.pojo.User;
import com.china.produce.service.UserService;
import com.china.produce.system.util.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2022/4/2
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserRealm.class);

    /**
     * 根据token判断此Authenticator是否使用该realm
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        logger.info("执行了授权 <<<");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();

        User currentUser = (User) subject.getPrincipal();

        info.addStringPermission(currentUser.getPerms());

        logger.info("perms : {}", currentUser.getPerms());

        return info;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        logger.info("执行了认证 ！");

        String token = (String) authenticationToken.getCredentials();

        logger.info("token: {}", token);

        if (!StringUtils.hasLength(token)) {
            throw new AuthenticationException("token 为空 ！");
        }

        User user = this.checkTokenIsEffect(token);

        return new SimpleAuthenticationInfo(user, token, user.getAccount());
    }

    /**
     * 解析token获取username
     *
     * @param token
     * @return
     */
    public User checkTokenIsEffect(String token) {
        String username = JwtUtil.getUsername(token);

        if (!StringUtils.hasLength(username)) {
            throw new AuthenticationException("token 失效");
        }

        User user = new User();

        user.setAccount(username);

        return user;
        // return userService.queryUserByName(username);
    }
}
